import qs from 'qs'

import * as auth from 'auth-provider'
import { useAuth } from 'context/auth-context'
import { useCallback } from 'react'
const apiUrl = process.env.REACT_APP_API_URL

interface Config extends RequestInit {
  data?: Record<string, unknown>
  token?: string
}

export const http = async (
  endpoint: string,
  { data, token, headers, ...customConfig }: Config = {}
) => {
  const config = {
    method: 'GET',
    headers: {
      Authorization: token ? `Bearer ${token}` : '',
      'Content-Type': data ? `application/json` : '',
    },
    ...customConfig,
  }

  if (config.method.toUpperCase() === 'GET') {
    const param = qs.stringify(data)
    endpoint += param ? `?${param}` : ''
  } else {
    config.body = JSON.stringify(data || {})
  }

  // axios 异常可以捕捉到 fetch 异常捕捉不到
  return window.fetch(`${apiUrl}/${endpoint}`, config).then(async (response) => {
    if (response.status === 401) {
      await auth.logout()
      window.location.reload()
      return Promise.reject({ message: '请重新登录' })
    }
    const responseData = await response.json()

    if (response.ok) {
      // 对收藏特殊处理
      if (endpoint.includes('projects/') && config.method.toUpperCase() === 'PATCH') {
        console.log(data, 'data', responseData)
        responseData['pin'] = data['pin']
        const projects = JSON.parse(localStorage.getItem('__jira__project')).map((item) => {
          if (item['id'] === data['id']) {
            item = responseData
          }
          return item
        })
        localStorage.setItem('__jira__project', JSON.stringify(projects))
      }
      return responseData
    } else {
      return Promise.reject(responseData)
    }
  })
}

export const useHttp = () => {
  const { user } = useAuth()

  return useCallback(
    (...[endpoint, config]: Parameters<typeof http>) =>
      http(endpoint, { ...config, token: user?.token }),
    [user?.token]
  )
}
